/**
 * 请求API 
 */
const API_HOST = 'http://localhost:13315'  // 本地地址
// const API_HOST = 'http://39.108.72.84:10015'  // 测试地址
const Auth = require('./auth')


const API = {}

API.getHost = function(){
	return API_HOST;
}

API.request = function(url, method = "GET", data={}, args = { token: true }) {
	
	return new Promise(function(resolve, reject) {
		
		url = API_HOST + url;
		
		if (args.token) {
			const token = API.token();
			if(token) {
				if(url.indexOf("?")>0) {
					url = url + '&access_token=' + token;
				} else {
					url = url + '?access_token=' + token;
				}
			} else {
				console.warn('[提示]','部分数据需要授权，检测出当前访问用户未授权登录小程序');
			}
		}
		console.log(url)
		console.log(data)
		API.getToken().then(res => {
			var headers = {
				'mp_Authorization': res.data
			}
			wx.request({
				url: url,
				data: data,
				method: method,
				header: headers,
				success: function(res) {
					console.log(res);
					if(res.statusCode == 200) {
						resolve(res.data);
					} else if(res.data.code === "rest_post_invalid_page_number") {
						wx.showToast({
							title: '没有更多内容',
							mask: false,
							duration: 1000
						});
					} else {
						wx.showToast({
							title: "请求数据失败",
							duration: 1500
						});
						console.log(res.data.message);
						reject(res.data);
					}
				},
				fail: function(err) {
					console.log(err);
					reject(err);
				}
			})
		});
	});
	
}

API.get = function(url, data={}, args = { token: false }) {
	return API.request(url, "GET", data, args);
}

API.post = function(url, data, args = { token: true }) {
	return API.request(url, "POST", data, args);
}

/**
 * 获取Token
 * @param  {object} args 参数
 * @return {promise}
 */
API.getToken = function() {
	return new Promise(function(resolve, reject) {
	wx.request({
		url: API_HOST +'/mp/common/v1/getToken',
		data: {},
		method: 'GET',
		success: function(res) {
			console.log('getToken->', res);
			resolve(res.data);
		},
		fail: function(err) {
			console.log(err);
		}
	})
})
}

/**
 * 获取用户信息
 */
API.getUser = function(){
	if(Auth.check()){
		return Auth.user();
	}else{
		return false;
	}
	
}

/**
 * 用户登录
 */
API.login = function() {
	return new Promise(function(resolve, reject) {
		if(Auth.check()){
			resolve(Auth.user());
		}else{
			Auth.login().then(data=>{
				console.log('wx.login->', data)
				API.post('/mp/l/v1/openId', data, { token: false }).then(res => {
					API.storageUser(res);
					resolve(res);
				}, err => {
					reject(err);
				});
			}).catch( err =>{
				reject(err);
			})
		}
	});
}

/**
 * 用户注销
 */
API.logout = function() {
	let logout = Auth.logout();
	if(logout) {
		getApp().globalData.user = '';
		wx.reLaunch({
			url: '/pages/index/index'
		})
	} else {
		wx.showToast({
			title: '注销失败!',
			icon: 'warn',
			duration: 1000,
		})
	}
}
/**
 * 获取用户信息(解密用户密文)
 */
API.getMiniUser = function() {
	return new Promise(function(resolve, reject) {
		Auth.getMiniEncryptedData().then(data=>{
			// data 用户数据密文
			data.sessionKey = wx.getStorageSync('session_key');
			data.openid = wx.getStorageSync('openid');
			console.log('getMiniUser params->', data);
			API.post('/mp/l/v1/getMiniUser', data, { token: false }).then(res => {
				if (res.code === 'M0002') {
						console.log(res.msg)
						API.login()
						API.getUserInfo()
				}else{
					API.storageUser(res);
					console.log('getUserInfo res->', res);
					resolve(res.user);
				}
			}, err => {
				reject(err);
			});
		})
		.catch( err =>{
			reject(err);
		})
	});
}

/**
 * 获取Token
 */
API.token = function() {
	let token = Auth.token();
	let datetime = Date.now();
	if(token && datetime < wx.getStorageSync('expired_in')) {
		return token;
	} else {
		return false;
	}
}

/**
 * 组合用户数据
 * @param {} res 
 */
API.storageUser = function(res) {
	if(res.data.user){
		getApp().globalData.user = res.data.user;
		wx.setStorageSync('user', res.data.user);
	}
	if(res.data.openid){
		wx.setStorageSync('openid', res.data.openid);
	}
	if(res.data.sessionKey){
		wx.setStorageSync('session_key', res.data.sessionKey);
	}
	if(res.data.code){
		wx.setStorageSync('js_code', res.data.code);
	}

	if(res.data.access_token){
		wx.setStorageSync('token', res.data.access_token);
		wx.setStorageSync('expired_in', Date.now() + parseInt(res.data.expired_in, 10) * 100000 - 60000);
	}
}

 /**
 * 需要授权的接口调用
 * @param	{Function} fn
 * @return {Promise}
 */
API.guard = function(fn) {
	const self = this
	return function() {
		if(API.getUser()) {
			return fn.apply(self, arguments)
		} else {
			return API.getUserInfo().then(res => {
				console.log('登录成功', res);
				return fn.apply(self, arguments)
			}, err => {
				console.log('登录失败', err);
				return err
			})
		}
	}
}

module.exports = API